package com.service;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;

import com.db.DbUtil;
import com.log.LogUtil;

public class ServiceImpl {
	private static ServiceImpl inst=new ServiceImpl();
	private static Object lock=new Object();
	private ServiceImpl(){}
	public static ServiceImpl inst(){
		if(inst==null){
			synchronized (lock) {
				inst= new ServiceImpl();
			}
		}
		return inst;
	}

	public  void loadDataFromFile(String filePath, String type) {
		try {			
			BufferedReader br = new BufferedReader(new FileReader(filePath));
			String s = null;
			ArrayList<Map<String, ?>> list = new ArrayList<Map<String, ?>>();
			while ((s = br.readLine()) != null) {
				String arr[] = s.trim().split("	", 3);
				String sql="select count(0) from data1 where type="+type+" and nper='"+arr[0]+"'";
				if(DbUtil.queryForInt(sql)>0)
					continue;
				String num[] = arr[1].split("\\|");
				if(num[0]==null || num[0].trim().equals("")) continue;
				Map<String, String> map = new HashMap<String, String>();
				map.put("type", type);
				map.put("nper", arr[0]);
				map.put("num1", num[0]);
				map.put("num2", num.length > 1 ? num[1] : "");
				map.put("tableName", "data1");
				list.add(map);				
			}
			LogUtil.info(DbUtil.insert(list));
		} catch (Exception e) {
			LogUtil.warn(e);
		}
	}
	public int insertLotteryData(Map<String, ?> map){
		int count=0;
		try {
			count= DbUtil.insert(map);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return count;
	}
	public Map<String,Integer> getData(int type,String year,int num){
		Map<String,Integer> data=	new HashMap<String,Integer>();		
		String yearStr="";
		if(StringUtils.isNotBlank(year)){
			yearStr="and substr(nper,1,2)="+year.substring(year.length()-2, year.length());
		}
		String limitStr="";
		if(num>0){
			limitStr=" limit 0,"+num;
		}
		StringBuffer sb=new StringBuffer();
		String baseSql="select count(0) field from (select * from data1 where type="+type+" "+yearStr+" order by nper desc "+limitStr+")a ";
		if(type==1){
			for(int i=1;i<=33;i++){
				sb.append("(").append(baseSql.replace("field","L"+(i>9?""+i:"0"+i))).append("where 1=1 and find_in_set('"+(i<10?"0"+i:i)+"',a.num1)").append(")num1").append(i).append(",");
			}
			for(int i=1;i<=16;i++){
				sb.append("(").append(baseSql.replace("field","R"+(i>9?""+i:"0"+i))).append("where 1=1 and find_in_set('"+(i<10?"0"+i:i)+"',a.num2)").append(")num2").append(i).append(",");
			}
		}else if(type==2){
			for(int i=1;i<=35;i++){
				sb.append("(").append(baseSql.replace("field","L"+(i>9?""+i:"0"+i))).append("where 1=1 and find_in_set('"+(i<10?"0"+i:i)+"',a.num1)").append(")num1").append(i).append(",");
			}
			for(int i=1;i<=12;i++){
				sb.append("(").append(baseSql.replace("field","R"+(i>9?""+i:"0"+i))).append("where 1=1 and find_in_set('"+(i<10?"0"+i:i)+"',a.num2)").append(")num2").append(i).append(",");
			}
		}
		if(sb.length()>0){
			sb.insert(0,"select * from ").deleteCharAt(sb.length()-1);
			try {
				System.out.println(sb.toString());
				data=DbUtil.queryForMap(sb.toString(),Integer.class);
			} catch (SQLException e) {
				LogUtil.warn(e);
			}
		}
		//System.out.println("list="+list);
		return data;

	}
	public Map<String,List<String>> getLatestData(int type){
		Map<String,List<String>> map=new HashMap<String,List<String>>();
		try {
			Map<String,String> dataMap=DbUtil.queryForMap("select num1,num2 from data1 where 1=1 and type="+type+" order by nper desc limit 1",String.class);
			map.put("num1", Arrays.asList(dataMap.get("num1").split(",")));
			map.put("num2", Arrays.asList(dataMap.get("num2").split(",")));		
		} catch (SQLException e) {
			LogUtil.warn(e);
		}
		//System.out.println("map="+map);
		return map;
	}
	public Set<String> getNearData(List<String> list,int type,int left_Right){
		Set<String> nearData=new HashSet<String>();
		int num=33;
		if(type==1){
			if(left_Right==1){
				num=33; 
			}else{
				num=16; 
			}
		}else if(type==2){
			if(left_Right==1){
				num=35; 
			}else{
				num=12; 
			}
		}
		for(String data:list){
			int i=Integer.parseInt(data);
			if(i-1>0){
				nearData.add(""+(i-1>9?(i-1):"0"+(i-1)));
			}else{
				nearData.add(""+num);
			}
			if(i+1<=num){
				nearData.add(""+(i+1>9?(i+1):"0"+(i+1)));
			}else{
				nearData.add("01");
			}
		}
		return nearData;
	}
	public Map<String, Integer> getHistoryData(int type ,int left_Right,String orderRule,String year ,int range){
		Map<String, Integer> map=new HashMap<String, Integer>();
		int num=33;
		String field="num1";
		if(type==1){
			if(left_Right==1){
				num=33;field="num1";
			}else{
				num=16;field="num2";
			}
		}else if(type==2){
			if(left_Right==1){
				num=35;field="num1";
			}else{
				num=12;field="num2";
			}
		}
		String yearStr="";
		if(StringUtils.isNotBlank(year)){
			yearStr="and substr(nper,1,2)="+year.substring(year.length()-2, year.length());
		}
		StringBuffer sb=new StringBuffer();
		for(int i=1;i<=num;i++){
			sb.append("select '").append(i>9?i:"0"+i).append("' as NO,count(0) as total from data1 where 1=1 ").append(yearStr).append(" and type=")
			.append(type).append(" AND FIND_IN_SET('").append(i>9?i:"0"+i).append("',").append(field).append(")")
			.append(" union ");
		}
		if(sb.length()>0){
			sb.insert(0,"select * from (").delete(sb.length()-6-1,sb.length()-1)
			.append(")a order by total ").append(orderRule).append(range>0?" limit "+range:"");
			//System.out.println(sb);
			try {
				map.putAll(DbUtil.queryForMaps(sb.toString(),Integer.class));
			} catch (SQLException e) {
				LogUtil.warn(e);
			}
		}
		return map;
	}
	public JSONObject getStatData(int type){
		/*（1）历史年度冷热号码优先度
		（2）本年度冷热号码优先度
		（3）上期开奖号码
		（4）上期的开奖号码的相邻号码
		（5）最近50期内冷热号码优先度分析
		（6）每个号码的遗漏次数*/
		JSONObject data=new JSONObject();
		//前区号码冷热号
		Map<String,Integer> history_hot_cold_1=getHistoryData(type, 1, "desc","", 4);
		history_hot_cold_1.putAll(getHistoryData(type, 1, "asc","", 4));
		data.put("his_hot_cold_1",history_hot_cold_1.keySet());
		//后区号码冷热号
		Map<String,Integer> history_hot_cold_2=getHistoryData(type, 2, "desc","", 4);
		history_hot_cold_2.putAll(getHistoryData(type, 2, "asc","", 4));
		data.put("his_hot_cold_2",history_hot_cold_2.keySet());
		//本年度前区冷热号码
		String year=""+Calendar.getInstance().get(Calendar.YEAR);
		Map<String,Integer> currentYear_hot_cold_1=getHistoryData(type, 1, "desc",year, 4);
		currentYear_hot_cold_1.putAll(getHistoryData(type, 1, "asc",year, 4));
		data.put("curYear_hot_cold_1", currentYear_hot_cold_1.keySet());
		//本年度后区冷热号码
		Map<String,Integer> currentYear_hot_cold_2=getHistoryData(type, 2, "desc",year, 4);
		currentYear_hot_cold_2.putAll(getHistoryData(type, 2, "asc",year, 4));
		data.put("curYear_hot_cold_2", currentYear_hot_cold_2.keySet());
		//上期开奖号码
		Map<String,List<String>> latestData=getLatestData(type);
		data.put("latest_1",latestData.get("num1"));
		data.put("latest_2",latestData.get("num2"));
		//上期开奖号码临近号码
		data.put("nearData_1", getNearData(latestData.get("num1"), type, 1));
		data.put("nearData_2", getNearData(latestData.get("num2"), type, 2));
		System.out.println("data="+data);
		//（5）最近50期内冷热号码优先度分析
		Map<String,Integer> latestNum1=getData2(1, 1,"", 50,"desc",5);
		latestNum1.putAll(getData2(1, 1,"", 50,"asc",5));
		data.put("latestNum_1", latestNum1.keySet());
		Map<String,Integer> latestNum2=getData2(1, 2,"", 50,"desc",5);
		latestNum2.putAll(getData2(1, 2,"", 50,"asc",5));
		data.put("latestNum_2", latestNum2.keySet());
		
		return data;
	}
	public Map<String ,Integer> getMissedData(int type){
		Map<String ,Integer>map=new HashMap<String, Integer>();
		String sql="select num1,num2 from data1 where type="+type+" order by nper desc";
		int left=33,right=16;		
		if(type==1){			
		}else{
			left=35;right=12;
		}
		int missedData1[]=new int[left];
		int missedData2[]=new int[right];
		Connection con=DbUtil.getConnection();
		ResultSet rs=null;
		try {
			rs=DbUtil.queryForRS(sql, con);
			while(rs!=null && rs.next()){
				
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return map;
	}
	public Map<String,Integer> getData2(int type,int left_Right,String year,int num,String order,int range){
		Map<String,Integer> data=	new HashMap<String,Integer>();		
		String yearStr="";
		if(StringUtils.isNotBlank(year)){
			yearStr="and substr(nper,1,2)="+year.substring(year.length()-2, year.length());
		}
		String limitStr="";
		if(num>0){
			limitStr=" limit 0,"+num;
		}
		int left=33,right=16;
		switch(type){
		case 1:left=33;right=16;break;
		case 2:left=35;right=12;break;
		default:left=33;right=16;break;
		}
		StringBuffer sb=new StringBuffer();
		String baseSql="select field as 'NO',count(0) total from (select * from data1 where type="+type+" "+yearStr+" order by nper desc "+limitStr+")a ";
		if(left_Right==1){
			for(int i=1;i<=left;i++){
				sb.append(baseSql.replace("field","'"+(i>9?""+i:"0"+i)+"'")).append("where 1=1 and find_in_set('"+(i<10?"0"+i:i)+"',a.num1)").append(" union ");
			}
		}else if(left_Right==2){
			for(int i=1;i<=right;i++){
				sb.append(baseSql.replace("field","'"+(i>9?""+i:"0"+i)+"'")).append("where 1=1 and find_in_set('"+(i<10?"0"+i:i)+"',a.num2)").append(" union ");
			}		
		}
		if(sb.length()>0){
			sb.insert(0,"select * from (").delete(sb.length()-7,sb.length()).append(" ) a order by total "+order+" limit "+range);
			try {
				System.out.println(sb.toString());
				data=DbUtil.queryForMaps(sb.toString(),Integer.class);
			} catch (SQLException e) {
				LogUtil.warn(e);
			}
		}
		//System.out.println("list="+list);
		return data;

	}
	public static void main(String[] args) throws IOException {
//		String filePath = "C:/Program Files (x86)/SSQ500WAN/Data/ssqHisData.lex";
//		String dltFilePath="C:/Program Files (x86)/DLT500WAN/Data/dltHisData.lex";
		//ServiceImpl.inst().loadDataFromFile(filePath,"1");
		//ServiceImpl.inst().loadDataFromFile(dltFilePath,"2");
		ServiceImpl.inst.getData2(1, 1,"", 50,"desc",5);
		ServiceImpl.inst.getData2(1, 1,"", 50,"asc",5);
		ServiceImpl.inst.getData2(1, 2,"", 50,"desc",5);
		ServiceImpl.inst.getData2(1, 2,"", 50,"asc",5);
//		System.out.println(ServiceImpl.inst().getHistoryData(1, 1,"desc", 4));;
		ServiceImpl inst=ServiceImpl.inst;
		//inst.getStatData(1);
		//inst.getLatestData(1);
	}

}
